package com.miyu.system.service.rule.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.blinkfox.fenix.specification.FenixSpecification;
import com.miyu.plugins.utils.Comutils;
import com.miyu.system.dao.rule.SysRuleDao;
import com.miyu.system.dao.rule.SysRuleModelDao;
import com.miyu.system.pojo.system.SysRule;
import com.miyu.system.pojo.system.SysRuleModel;
import com.miyu.system.service.rule.SysRuleService;
import com.miyu.system.utils.crawler.CrawlerUtils;
import com.miyu.system.utils.enumeration.R;
import com.miyu.system.utils.page.PageLimit;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统规则服务
 * @author miyu
 */
@Service
@RequiredArgsConstructor
public class SysRuleServiceImpl implements SysRuleService {
    private final SysRuleDao dao;
    private final SysRuleModelDao modelDao;
    /**
     * 系统规则编辑
     * 注解批量删除缓存
     * @param sysRule 系统规则
     * @return {@link SysRule}
     */
    @Override
    @Caching(evict={@CacheEvict(cacheNames = "system:sysRule" ,key="'sysRule'")})
    @CachePut(cacheNames = "system:sysRule" ,key="#result.getRuleId()")
    public SysRule sysRuleEdit(SysRule sysRule) {
        String userId = Comutils.getUUID();
        if(sysRule.getRuleId()==null){
            sysRule = dao.save(sysRule);
            //创建分表
            createTableModel(sysRule);
        }
//        if(StrUtil.isBlank(sysRule.getRuleId())){
//            sysRule.setRuleId(userId);
//        }
//        sysRule = dao.saveOrUpdateByNotNullProperties(sysRule);
        return sysRule;
    }

    private void createTableModel(SysRule sysRule) {

        Integer ruleId = sysRule.getRuleId();
        //书籍表分三张表
        //1 书籍明细表
        creataTableMain(ruleId);
        //2 书籍章节表
        createTableChapter(ruleId);
        //3 书籍阅读表
//        createTableReader(tableId);
    }

    /**
     * 书籍主表创建
     */
    private void creataTableMain(Integer tableId) {
        dao.doExecute("create table book_main_" + tableId + " like book_main ");
    }

    /**
     * 书籍章节表
     * @param tableId
     */
    private void createTableChapter(Integer tableId) {

        List<String> sqlList = new ArrayList<String>();

        String[] table = CrawlerUtils.BOOK_CHAPTER;
        for (String s : table) {
            String sql = "create table book_chapter_" + tableId + "_" + s + " like book_chapter ";
            sqlList.add(sql);
        }
        dao.doExecuteBatch(sqlList);
    }

    /**
     * 查询系统规则
     *
     * @param param 参数
     * @return {@link JSONArray}
     */
    @Override
    public Page<SysRule> querySysRule(JSONObject param) {

        //分页信息
        Pageable pageable = PageLimit.pageable(param);
        return dao.findAll(FenixSpecification.of(builder
                        ->builder.andLike("ruleName",param.get("ruleName"),StrUtil.isNotBlank(param.getString("ruleName")))
                        .andEquals("ruleType",param.get("ruleType"),StrUtil.isNotBlank(param.getString("ruleType")))
                        .build())
                ,pageable);
    }

    /**
     * 删除系统规则
     * @param params 参数
     * @return {@link JSONObject}
     */
    @Override
    @CacheEvict(cacheNames="system:sysRule",key="'sysRule'")
    public JSONObject delSysRule(JSONArray params) {
        List<SysRule> sysRuleList = params.toJavaList(SysRule.class);
        //删除分表
       // delTableModel(sysRuleList);
        dao.deleteAllInBatch(sysRuleList);
        return R.result("101");
    }

    /**
     * 获取系统规则通过id
     * @param ruleId 规则id
     * @return {@link SysRule}
     */
    @Override
    @Cacheable(value  = "system:sysRule" ,key = "#ruleId")
    public SysRule getSysRuleById(Integer ruleId) {
        SysRule rule =  new SysRule();
        rule.setRuleId(ruleId);
        Example<SysRule> example = Example.of(rule);
        return dao.findOne(example).orElse(null);
    }

    /**
     * 查询规则模型通过密码
     * @param modelCode 型号代码
     * @return 系统规则模型
     */
    @Override
    public SysRuleModel queryRuleModelByCode(String modelCode) {
        SysRuleModel model = new SysRuleModel();
        model.setModCode(modelCode);
        Example<SysRuleModel> example = Example.of(model);

        SysRuleModel ruleModel = modelDao.findOne(example).orElse(null);
        return ruleModel;
    }

}
